import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import java.util.Random;

public class Publisher
{

    private static String brokerURL = "tcp://localhost:61616";
    private static ConnectionFactory factory;
    private Connection connection;
    private Session session;
    private MessageProducer producer;
    private Topic topic;
    private Random random = new Random(System.nanoTime());
    private int a = 50;//均值
    private int b = 5;//方差

    public Publisher(String topicName) throws JMSException
    {

        factory = new ActiveMQConnectionFactory(brokerURL);
        connection = factory.createConnection();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        topic = session.createTopic(topicName);
        producer = session.createProducer(topic);

        connection.start();
    }

    public void close() throws JMSException
    {
        if (connection != null)
        {
            connection.close();
        }
    }

    public static void main(String[] args) throws JMSException
    {
        Publisher publisher = new Publisher("MYTOPIC");
        try
        {
            while (true)
            {
                publisher.sendMessage();
                Thread.sleep(10);
            }
        }
        catch (Exception e)
        {
            publisher.close();
        }

    }

    public void sendMessage() throws JMSException
    {
        double num = Math.sqrt(b) * random.nextGaussian() + a;
        Message message = session.createTextMessage(String.valueOf(num));

        producer.send(message);
        System.out.println("Sent a message: " + num);

    }
}
